﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
using ChinapnrAPI;
using DTCash.Logger;
using DTCash.Logger.DTO;
using DTCash.Logger.NodeLog.Model;
using DTCash.Logger.NodeLog;
using Uranus.Common;
using Uranus.ChinaService.Receives;

namespace Uranus.ChinaService
{
    public class ChinaServiceCommon
    {
        /// <summary>
        /// 日志记录
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="nodeLogType"></param>
        /// <param name="httpRequest"></param>
        /// <param name="t"></param>
        public static void WriteLog(string title, string content, DTCash.Logger.DTO.LogEnum logEnum, Dictionary<string, string> t, HttpRequest httpRequest, bool isSendEmail)
        {
            t = t ?? new Dictionary<string, string>();
            t.Add("UrlReferrer", httpRequest.UrlReferrer != null ? httpRequest.UrlReferrer.ToString() : string.Empty);
            //t.Add("UserHostAddress", httpRequest.UserHostAddress);
            //t.Add("ServerIP", VisitCommon.GetIp());
            //t.Add("ServiceName", VisitCommon.GetServiceName());
            LogHelper.WriteLog(logEnum, title, content, t, isSendEmail);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="t"></param>
        /// <param name="httpRequest"></param>
        public static void WriteInfoLog(string title, string content, Dictionary<string, string> t, HttpRequest httpRequest)
        {
            WriteLog(title, content, LogEnum.Info, t, httpRequest, false);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="t"></param>
        /// <param name="httpRequest"></param>
        public static void WriteErrorLog(string title, string content, dynamic t, HttpRequest httpRequest, bool isSendEmail)
        {
            WriteLog(title, content, LogEnum.Error, t, httpRequest, isSendEmail);
        }



        /// <summary>
        /// 服务器IP地址
        /// </summary>
        public static string ServerIp
        {
            get { return Common.VisitCommon.GetIp(); }
        }

        /// <summary>
        /// 服务器名称
        /// </summary>
        public static string ServerName
        {
            get { return Common.VisitCommon.GetServiceName(); }
        }


        ///// <summary>

        /// <summary>
        /// 获取访问用户IP
        /// </summary>
        /// <param name="httpRequest"></param>
        /// <returns></returns>
        public static string GetIp(HttpRequest httpRequest)
        {
            try
            {
                if (httpRequest == null)
                {
                    return "127.0.0.1";
                }
                else
                    return httpRequest.UserHostAddress;
            }
            catch
            {
                return "127.0.0.1";
            }
        }
        /// <summary>
        /// 获取访问用户IP
        /// </summary>
        /// <param name="httpRequest"></param>
        /// <returns></returns>
        public static string GetIp(HttpRequestBase httpRequest)
        {
            try
            {
                if (httpRequest == null)
                {
                    return "127.0.0.1";
                }
                else
                    return httpRequest.UserHostAddress;
            }
            catch
            {
                return "127.0.0.1";
            }
        }

        public static void MethodRequest(string cmdid, HttpContext httpContext)
        {
            switch (cmdid)
            {
                case "UserRegister":
                    new UserManagerReceive(httpContext).UserRegister();
                    break;
                case "InitiativeTender":
                    new TransferReceive(httpContext).InitiativeTender();
                    break;
                case "Loans":
                    new LoansRepaymentReceive(httpContext).Loans();
                    break;
                case "Repayment":
                    new LoansRepaymentReceive(httpContext).Repayment();
                    break;
                case "AddBidInfo":
                    new BidOperationReceive(httpContext).AddBidInfo();
                    break;
                case "NetSave":
                    new TransferReceive(httpContext).NetSave();
                    break;
                case "Cash":
                    new TransferReceive(httpContext).Cash();
                    break;
                case "MerCash":
                    new TransferReceive(httpContext).MerCash();
                    break;
                case "UsrFreezeBg":
                    new TransferReceive(httpContext).UsrFreezeBg();
                    break;
                case "UsrUnFreeze":
                    new TransferReceive(httpContext).UsrUnFreeze();
                    break;
                case "PnrUsrUnBindExpressCard":
                    new TransferReceive(httpContext).PnrUsrUnBindExpressCard();
                    break;
            }
        }

        /// <summary>
        /// 汇付访问日志
        /// </summary>
        /// <param name="httpContext"></param>
        public static BaseChinapnr WriteLogByContent(HttpContext httpContext)
        {
            try
            {
                BaseChinapnr chinapnr = new BaseChinapnr();
                chinapnr.SetRequest(httpContext.Request);
                chinapnr.RetUrl = Common.CodeCommon.UrlDeCode(chinapnr.RetUrl ?? string.Empty);
                chinapnr.BgRetUrl = Common.CodeCommon.UrlDeCode(chinapnr.BgRetUrl ?? string.Empty);
                chinapnr.MerPriv = Common.CodeCommon.UrlDeCode(chinapnr.MerPriv ?? string.Empty);
                chinapnr.RespDesc = Common.CodeCommon.UrlDeCode(chinapnr.RespDesc ?? string.Empty);
                chinapnr.SecRespDesc = Common.CodeCommon.UrlDeCode(chinapnr.SecRespDesc ?? string.Empty);
                NameValueCollection nameValueCollection = new NameValueCollection();
                StringBuilder builder = new StringBuilder();
                if ("post".Equals(httpContext.Request.HttpMethod.ToLower()))
                {
                    nameValueCollection = httpContext.Request.Form;
                }
                else
                {
                    nameValueCollection = httpContext.Request.QueryString;
                }
                foreach (string key in nameValueCollection.AllKeys)
                {
                    builder.AppendFormat("{0}:{1}\r\n", key, HttpUtility.UrlDecode(nameValueCollection[key], Encoding.UTF8));
                }
                VisitCommon visit = new VisitCommon();
                visit.SetVisit(httpContext.Request);

                LogHelper.WriteLog(LogEnum.Visit, "visit", builder.ToString(), visit);

                WriteHuiFuResponse(chinapnr, builder.ToString());
                return chinapnr;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLogError("汇付回调站点访问日志解析异常", ex.Message, ex, true);
            }
            return null;
        }

        public static void WriteHuiFuResponse(BaseChinapnr baseChinapnr, string result)
        {
            HuiFuResponseDTO huiFuResponseDTO = new HuiFuResponseDTO(baseChinapnr, result);
            //huiFuResponseDTO.Result = "";
            //移除_id 防止主键ID生成错误
            huiFuResponseDTO.Result = "";
            Dictionary<string, object> dic =
                NodeLogTool.DeSerialize<Dictionary<string, object>>(NodeLogTool.Serialize((object)huiFuResponseDTO));
            if (dic != null && dic.ContainsKey("_id"))
            {
                dic.Remove("_id");
            }
            NodeLogHandler.AddLog("ajchuifu", "huifuinfo", "back", "", NodeLogType.info, dic);
        }
    }
}